package zy.service.wx.coupon.impl;

import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;

import zy.dao.wx.coupon.WxCouponDAO;
import zy.entity.sell.ecoupon.T_Sell_ECouponList;
import zy.entity.sell.ecoupon.T_Sell_Ecoupon_User;
import zy.service.wx.coupon.WxCouponService;
import zy.util.CheckCodeUtil;
import zy.util.CommonUtil;
import zy.util.DateUtil;

@Service
public class WxCouponServiceImpl implements WxCouponService {

	@Resource
	private WxCouponDAO wxCouponDAO;
	
	@Override
	public List<T_Sell_ECouponList> getCouponCenterList(
			Map<String, Object> params) {
		Assert.notNull(params.get(CommonUtil.COMPANYID), "连接超时，请重新登录!");
		Assert.notNull(params.get(CommonUtil.SHOP_CODE), "参数shop_code不能为null");
		Assert.notNull(params.get("wu_mobile"), "手机号码不能为空!");
		return wxCouponDAO.getCouponCenterList(params);
	}

	@Override
	@Transactional
	public void drawCoupon(Map<String, Object> params) {
		Assert.notNull(params.get(CommonUtil.COMPANYID), "连接超时，请重新登录!");
		Assert.notNull(params.get(CommonUtil.SHOP_CODE), "参数shop_code不能为null");
		Assert.notNull(params.get("ecl_code"), "优惠券编号不能为空");
		Assert.notNull(params.get("wu_mobile"), "手机号码不能为空!");
		String ecl_code = (String)params.get("ecl_code");
		Integer companyid = (Integer)params.get(CommonUtil.COMPANYID);
		T_Sell_ECouponList eCouponList = wxCouponDAO.loadDetail(ecl_code,companyid);
		if (eCouponList == null) {
			throw new RuntimeException("优惠券不存在");
		}
		int receivedCount = wxCouponDAO.countECouponReceived(ecl_code, companyid);
		if (receivedCount >= eCouponList.getEcl_amount()) {
			throw new RuntimeException("优惠券已被领完");
		}
		String wu_mobile = (String)params.get("wu_mobile");
		String wu_nickname = (String)params.get("wu_nickname");
		String shop_code = (String)params.get(CommonUtil.SHOP_CODE);
		T_Sell_Ecoupon_User t_Sell_Ecoupon_User = new T_Sell_Ecoupon_User();
		t_Sell_Ecoupon_User.setEcu_ec_number(eCouponList.getEcl_number());
		t_Sell_Ecoupon_User.setEcu_code(eCouponList.getEcl_code());
		t_Sell_Ecoupon_User.setEcu_date(DateUtil.getYearMonthDate());
		t_Sell_Ecoupon_User.setEcu_name(wu_nickname);
		t_Sell_Ecoupon_User.setEcu_tel(wu_mobile);
		t_Sell_Ecoupon_User.setEcu_money(eCouponList.getEcl_money());
		t_Sell_Ecoupon_User.setEcu_limitmoney(eCouponList.getEcl_limitmoney());
		t_Sell_Ecoupon_User.setEcu_shop_code(shop_code);
		t_Sell_Ecoupon_User.setEcu_begindate(eCouponList.getEc_begindate());
		t_Sell_Ecoupon_User.setEcu_enddate(eCouponList.getEc_enddate());
		t_Sell_Ecoupon_User.setEcu_state(0);
		t_Sell_Ecoupon_User.setEcu_check_no(CheckCodeUtil.buildCheckCode(4));
		t_Sell_Ecoupon_User.setCompanyid(companyid);
		wxCouponDAO.save_ecoupon_user(t_Sell_Ecoupon_User);
	}
}
